package com.himore.api.web.service;

import com.alibaba.fastjson.JSONObject;
import com.himore.api.common.annotation.Log;
import com.himore.api.common.constant.UserConstants;
import com.himore.api.common.core.domain.AjaxResult;
import com.himore.api.common.core.domain.entity.SysUser;
import com.himore.api.common.enums.BusinessType;
import com.himore.api.common.utils.DateUtils;
import com.himore.api.system.service.ISysUserService;
import com.himore.api.web.model.PushServiceInfoVO;
import com.himore.api.web.model.TAccountBook;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service//将这个对象加入Spring容器中
public class PushMsgSchedule {

    @Autowired
    ISysUserService  userService;
    @Autowired
    private ITAccountBookService tAccountBookService;
    @Resource
    private HttpAPIService httpAPIService;

    private static final Logger LOGGER = LoggerFactory.getLogger(PushMsgSchedule.class);

    //每天上午十点遍历用户表查询是否是带有
    //@Scheduled(cron = "0 0 10 ? * *" )
    @Log(title = "每天自动添加工资信息", businessType = BusinessType.INSERT)
    public void demoSchedule() {
        LOGGER.info(LocalDate.now() +",今日的消息推送开始了！");
        SysUser sysUser = new SysUser();
        sysUser.setNeedService("1");
        List<SysUser> userList =userService.selectUserList(sysUser);
        String  res ="";
        String accessToken = getAccessToken();
        for(SysUser user :userList){
                pushServiceMsg(user,accessToken);
        }
        LOGGER.info(LocalDate.now() +",今日的消息推送结束了！");
    }

    //每天0点遍历用户表 给每一个用户根据用户的基本工资，添加一条工资信息。
    @Scheduled(cron = "01 0 0 ? * *" )
    public void addSalarySchedule() {
        LOGGER.info(LocalDate.now() +",自动添加工资数据开始了！");
        SysUser sysUser = new SysUser();
        List<SysUser> userList =userService.selectUserList(sysUser);
        String  res ="";
        int days =LocalDate.now().withMonth(LocalDate.now().getMonthValue()).lengthOfMonth();
        for(SysUser user :userList){
            Map param = new HashMap();
            param.put("userId",user.getUserId());
            param.put("accountTime",DateUtils.getStandarDate());
            if(null!= user.getBasePay() && 0.00 != user.getBasePay().doubleValue()  && !tAccountBookService.checkSalaryExists(param)){
                TAccountBook tAccountBook = new TAccountBook();
                tAccountBook.setIsIncome(1);
                tAccountBook.setIncomeType("2");
                tAccountBook.setIncomeTypeName("工资");
                tAccountBook.setInputSum(user.getBasePay().doubleValue()/days);
                tAccountBook.setAccountTime(DateUtils.getStandarDate());
                tAccountBook.setUserId(user.getUserId());
                tAccountBookService.simpleInsertTAccountBook(tAccountBook);
            }
        }

        LOGGER.info(LocalDate.now() +",今日自动添加工资数据结束了！");
    }



    public AjaxResult pushServiceMsg(SysUser sysUser,String accessToken){

        PushServiceInfoVO pushServiceInfoVO  = new PushServiceInfoVO();
        try {
            HashMap queryParam = new HashMap();
            queryParam.put("userId",sysUser.getUserId());
            pushServiceInfoVO = tAccountBookService.getPushServiceInfo(queryParam);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("查询昨天和当月信息异常,请联系管理员！");
        }

        JSONObject sendParam = new  JSONObject();
        sendParam.put("template_id",UserConstants.WX_DTEMPLATE_ID);
        sendParam.put("touser",sysUser.getOpenId());
        JSONObject mpTemplateMsg = new JSONObject();
        mpTemplateMsg.put("appid",UserConstants.WX_PUBLIC_APP_ID);
        mpTemplateMsg.put("template_id",UserConstants.WX_TEMPLATE_ID);
        mpTemplateMsg.put("url",UserConstants.WX_DOWN_URL);
        JSONObject miniprogram = new JSONObject();
        miniprogram.put("appid",UserConstants.WX_APPID);
        //miniprogram.put("pagepath","index?foo=bar");
        mpTemplateMsg.put("miniprogram",miniprogram);

        JSONObject params =new JSONObject();

        JSONObject first =new JSONObject();
        first.put("value","您好，欢迎使用混世模王记账工具，您的昨日账单已生成！");
        first.put("color","#173177");
        params.put("first",first);

        JSONObject keyword1 =new JSONObject();
        keyword1.put("value","工作收入");
        keyword1.put("color","#173177");
        params.put("keyword1",keyword1);

        JSONObject keyword2 =new JSONObject();
        keyword2.put("value",pushServiceInfoVO.getThing2()+"");
        keyword2.put("color","#173177");
        params.put("keyword2",keyword2);

        JSONObject keyword3 =new JSONObject();
        keyword3.put("value",pushServiceInfoVO.getThing1());
        keyword3.put("color","#173177");
        params.put("keyword3",keyword3);



        JSONObject remark =new JSONObject();
        remark.put("value","如需查看详情，请点击下方小程序！");
        remark.put("color","#173177");
        params.put("remark",remark);

        mpTemplateMsg.put("data",params);

        sendParam.put("mp_template_msg", mpTemplateMsg);
        try {
            String url = UserConstants.WX_PUBLIC_URL + "?access_token=" + accessToken;
            String result = httpAPIService.HttpPostWithJson(url, sendParam.toJSONString());

            System.out.println("result=====" + result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String errorCode = jsonObject.getString("errcode");
            String errormsg = jsonObject.getString("errcode");
            if (UserConstants.WX_ERROR_CODE.equals(errorCode)) {
                //如果accessToken 失效，重新获取并重新执行推送操作
                String newToken = getAccessToken();
                pushServiceMsg(sysUser, newToken);
            }
            return AjaxResult.success();
        } catch (Exception e) {
            return AjaxResult.error();
        }
    }



    public  String  getAccessToken(){
        String res="";
        HashMap param = new HashMap();
        param.put("grant_type","client_credential");
        param.put("appid",UserConstants.WX_APPID);
        param.put("secret",UserConstants.WX_APP_SECRET);
        try{
            res = httpAPIService.doGet(UserConstants.WX_ACCESS_URL,param);
        }catch (Exception e){
            e.printStackTrace();
        }

        JSONObject jsonObject = JSONObject.parseObject(res);
        String  accessToken = jsonObject.getString("access_token");
        return  accessToken;
    }


    public static void main(String[] args) {
        int days =LocalDate.now().withMonth(LocalDate.now().getMonthValue()).lengthOfMonth();
        SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD") ;
        try {
            Date  dateee= sdf.parse(DateUtils.getDate());
            System.out.println(dateee);
            System.out.println(DateUtils.getDate());


        }catch (Exception w){
            w.printStackTrace();
        }

    }
}
